package com.ssyu.examination.questionbank.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.ssyu.examination.conmmon.App;
import com.ssyu.examination.conmmon.AppServlet;
import com.ssyu.examination.conmmon.Constants;
import com.ssyu.examination.conmmon.PageModel;
import com.ssyu.examination.conmmon.util.DBUtil;
import com.ssyu.examination.conmmon.util.FastjsonUtil;
import com.ssyu.examination.questionbank.entity.QesExamPaperEntity;
import com.ssyu.examination.questionbank.entity.QuestionQesEntity;
import com.ssyu.examination.questionbank.service.QesExamPaperService;
import com.ssyu.examination.system.entity.CourseEntity;
import com.ssyu.examination.system.service.ClazzService;

@WebServlet("/QesExamPaperServlet")
public class QesExamPaperServlet extends AppServlet {
	private static final long serialVersionUID = 1L;
	private static QesExamPaperService examPaperService = new QesExamPaperService();
	private static ClazzService clazzService = new ClazzService();

	public QesExamPaperServlet() {
		super();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constants.ENCODE_UTF8);
		String command = request.getParameter("command");
		if ("listpaper".equals(command)) {
			listpaper(request, response);
		} else if ("listMenu".equals(command)) {
			listMenu(request, response);
		} else if ("getpaper".equals(command)) {
			getpaper(request, response);
		} else if ("updatePaperState".equals(command)) {
			updatePaperState(request, response);
		} else if ("addpaper".equals(command)) {
			addpaper(request, response);
		} else if ("accordAddPaper".equals(command)) {
			accordAddPaper(request, response);
		} else if ("rebuildPaper".equals(command)) {
			rebuildPaper(request, response);
		} else if ("previewPaper".equals(command)) {
			previewPaper(request, response);
		}
	}

	/**
	 * 列举所有试卷信息
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listpaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int page = Integer.parseInt(request.getParameter("page"));
		int rows = Integer.parseInt(request.getParameter("rows"));
		String paperName = request.getParameter("paperName");
		String courseStr = request.getParameter("courseId");
		int courseId = 0;
		if (StringUtils.isNotBlank(courseStr)) {
			courseId = Integer.parseInt(courseStr);
		}
		String stateStr = request.getParameter("state");
		int state = 1;
		if (StringUtils.isNotBlank(stateStr)) {
			state = Integer.parseInt(stateStr);
		}

		PageModel<QesExamPaperEntity> pageModel = examPaperService.listpaper(
				page, rows, paperName, courseId, state);

		print(response, FastjsonUtil.toJsonWithDateFormat(pageModel,
				"yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 生成课程树
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listMenu(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = 0;
		String idStr = request.getParameter("id");
		if (idStr != null) {
			id = Integer.parseInt(idStr);
		}

		List<CourseEntity> menuList = clazzService.listMenu(id);

		print(response, FastjsonUtil.toJson(menuList));

	}

	/**
	 * 根据ID查看试卷详情
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void getpaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		QesExamPaperEntity qesExamPaperEntity = examPaperService.getPaper(id);
		if (qesExamPaperEntity != null) {
			print(response, FastjsonUtil.toJsonWithDateFormat(
					qesExamPaperEntity, "yyyy-MM-dd HH:mm:ss"));
		}

	}

	/**
	 * 修改试卷状态
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePaperState(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		int states = Integer.parseInt(request.getParameter("state"));
		int state = 0;
		if (states == 1) {
			state = 2;
		} else if (states == 2) {
			state = 1;
		}

		int operateId = App.getOperateId(request, response);
		int row = examPaperService.updateClazzState(id, state, operateId);

		if (row > 0) {
			print(response, 1);
		}

	}

	private void addpaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Object> paramList = new ArrayList<Object>();
		String name = request.getParameter("name");
		paramList.add(name);

		String dateStr = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		String fileName = name + dateStr + ".json";
		String url = "E:/examination/" + fileName;
		paramList.add(url);
		int type = Integer.parseInt(request.getParameter("type"));
		paramList.add(type);
		int course = Integer.parseInt(request.getParameter("course"));
		paramList.add(course);
		int totalPoint = Integer.parseInt(request.getParameter("totalPoint"));
		paramList.add(totalPoint);
		int passPoint = Integer.parseInt(request.getParameter("passPoint"));
		paramList.add(passPoint);
		int totalMinutes = Integer.parseInt(request
				.getParameter("totalMinutes"));
		paramList.add(totalMinutes);
		int singleNumber = Integer.parseInt(request
				.getParameter("singleNumber"));
		paramList.add(singleNumber);
		int singlePoint = Integer.parseInt(request.getParameter("singlePoint"));
		paramList.add(singlePoint);
		int singleDifficulty = Integer.parseInt(request
				.getParameter("singleDifficulty"));
		paramList.add(singleDifficulty);
		int multiNumber = Integer.parseInt(request.getParameter("multiNumber"));
		paramList.add(multiNumber);
		int multiPoint = Integer.parseInt(request.getParameter("multiPoint"));
		paramList.add(multiPoint);
		int multiDifficulty = Integer.parseInt(request
				.getParameter("multiDifficulty"));
		paramList.add(multiDifficulty);
		int judgeNumber = Integer.parseInt(request.getParameter("judgeNumber"));
		paramList.add(judgeNumber);
		int judgePoint = Integer.parseInt(request.getParameter("judgePoint"));
		paramList.add(judgePoint);
		int judgeDifficulty = Integer.parseInt(request
				.getParameter("judgeDifficulty"));
		paramList.add(judgeDifficulty);
		int id = App.getOperateId(request, response);
		paramList.add(id);
		
		//分数验证
		boolean flag=examPaperService.checkPoint(totalPoint,singleNumber,singlePoint,multiNumber,multiPoint,judgeNumber,judgePoint);
		if(flag){

		List<QuestionQesEntity> singleList = examPaperService.singleList(
				course, singleDifficulty, singleNumber);
		List<QuestionQesEntity> miltiList = examPaperService.miltipleList(
				course, multiDifficulty, multiNumber);
		List<QuestionQesEntity> judgeList = examPaperService.judgeList(course,
				judgeDifficulty, judgeNumber);

		long row = examPaperService.addpaper(paramList);
		QesExamPaperEntity qesExamPaperEntity = DBUtil.getUniqueResult(
				QesExamPaperEntity.class,
				"select * from qes_exam_paper where id=?", row);
		qesExamPaperEntity.setSingleList(singleList);
		qesExamPaperEntity.setMultipleList(miltiList);
		qesExamPaperEntity.setJudgeList(judgeList);

		examPaperService.addPaperFile(FastjsonUtil.toJsonWithDateFormat(
				qesExamPaperEntity, "yyyy-MM-dd HH:mm"), fileName);
		if (row > 0) {
			print(response, 1);
		}
		}else{
			print(response, false);
		}
		
		

	}

	private void previewPaper(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		QesExamPaperEntity qesExamPaperEntity = examPaperService
				.previewPaper(id);
		if (qesExamPaperEntity != null) {
			String URL = qesExamPaperEntity.getPaperUrl();
			try {

				File file = new File(URL);
				if (file.isFile() && file.exists()) { // 判断文件是否存在
					InputStreamReader read = new InputStreamReader(
							new FileInputStream(file), Constants.ENCODE_UTF8);// 考虑到编码格式
					BufferedReader bufferedReader = new BufferedReader(read);
					String lineTxt = null;
					StringBuilder str = new StringBuilder();
					while ((lineTxt = bufferedReader.readLine()) != null) {
						str.append(lineTxt);
					}
					print(response, FastjsonUtil.toJsonWithDateFormat(str,
							"yyyy-MM-dd HH:mm"));
					read.close();
				} else {
					print(response, false);
				}
			} catch (Exception e) {
				System.out.println("读取文件内容出错");
				e.printStackTrace();
			}
		}

	}

	/**
	 * 自动生成试卷
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void accordAddPaper(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<Object> paramList = new ArrayList<Object>();
		String name = request.getParameter("name");
		paramList.add(name);

		String dateStr = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		String fileName = name + dateStr + ".json";
		String url = "E:/examination/" + fileName;
		paramList.add(url);
		int type = Integer.parseInt(request.getParameter("type"));
		paramList.add(type);
		int course = Integer.parseInt(request.getParameter("course"));
		paramList.add(course);
		int id = App.getOperateId(request, response);
		paramList.add(id);

		List<QuestionQesEntity> singleList = examPaperService
				.singleList(course);
		List<QuestionQesEntity> miltiList = examPaperService
				.miltipleList(course);
		List<QuestionQesEntity> judgeList = examPaperService.judgeList(course);

		long row = examPaperService.accordAddPaper(paramList);
		QesExamPaperEntity qesExamPaperEntity = DBUtil.getUniqueResult(
				QesExamPaperEntity.class,
				"select * from qes_exam_paper where id=?", row);
		qesExamPaperEntity.setSingleList(singleList);
		qesExamPaperEntity.setMultipleList(miltiList);
		qesExamPaperEntity.setJudgeList(judgeList);

		examPaperService.addPaperFile(FastjsonUtil.toJsonWithDateFormat(
				qesExamPaperEntity, "yyyy-MM-dd HH:mm"), fileName);
		if (row > 0) {
			print(response, 1);
		}
	}

	/**
	 * 重新生成试卷
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void rebuildPaper(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		QesExamPaperEntity qesExamPaperEntity = examPaperService.getPaper(id);
		if (qesExamPaperEntity != null) {
			String name = qesExamPaperEntity.getName();
			String dateStr = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(new Date());
			String fileName = name + dateStr + ".json";
			String oldUrl = qesExamPaperEntity.getPaperUrl();
			String url = "E:/examination/" + fileName;

			int course = qesExamPaperEntity.getCourseId();

			int singleDifficulty = qesExamPaperEntity
					.getSingleOptionDifficulty();
			if (singleDifficulty == 0) {
				List<QuestionQesEntity> singleList = examPaperService
						.singleList(course);
				List<QuestionQesEntity> miltiList = examPaperService
						.miltipleList(course);
				List<QuestionQesEntity> judgeList = examPaperService
						.judgeList(course);

				qesExamPaperEntity.setSingleList(singleList);
				qesExamPaperEntity.setMultipleList(miltiList);
				qesExamPaperEntity.setJudgeList(judgeList);
				String fast = FastjsonUtil.toJsonWithDateFormat(
						qesExamPaperEntity, "yyyy-MM-dd HH:mm");
				examPaperService.rebuildPaperFile(fast, fileName, oldUrl);

				// 修改表内信息
				int row = examPaperService.updateUrl(url, id);
				if (row == 1) {
					print(response, 1);
				}
			} else {
				int singleNumber = qesExamPaperEntity.getSingleOptionNumber();
				int multiDifficulty = qesExamPaperEntity
						.getMultiOptionDifficulty();
				int multiNumber = qesExamPaperEntity.getMultiOptionNumber();
				int judgeDifficulty = qesExamPaperEntity.getJudgeDifficulty();
				int judgeNumber = qesExamPaperEntity.getJudgeNumber();
				List<QuestionQesEntity> singleList = examPaperService
						.singleList(course, singleDifficulty, singleNumber);
				List<QuestionQesEntity> miltiList = examPaperService
						.miltipleList(course, multiDifficulty, multiNumber);
				List<QuestionQesEntity> judgeList = examPaperService.judgeList(
						course, judgeDifficulty, judgeNumber);

				qesExamPaperEntity.setSingleList(singleList);
				qesExamPaperEntity.setMultipleList(miltiList);
				qesExamPaperEntity.setJudgeList(judgeList);

				String fast = FastjsonUtil.toJsonWithDateFormat(
						qesExamPaperEntity, "yyyy-MM-dd HH:mm");
				examPaperService.rebuildPaperFile(fast, fileName, oldUrl);

				// 修改表内信息
				int row = examPaperService.updateUrl(url, id);
				if (row == 1) {
					print(response, 1);
				}
			}

		}
	}

}
